<template>
  <div class="content-view">
    <!-- 工具栏 -->
    <div class="tool-bar">
      <div class="view">
        <el-input placeholder="按名称关键字筛选" v-model="searchKey.words" clearable>
          <template #suffix>
            <i class="iconfont icon-sousuo"></i>
          </template>
        </el-input>
        <!-- 条件搜索 -->
        <condition-query :data="data" @search="searchDone" />
      </div>
      <div class="view end">
        <!-- <el-button type="primary" @click="handleBtn(0, {name: ''}, 'add')" v-if="user.power*1 > 80">
          <i class="iconfont icon-xinjian"></i>新建用户
        </el-button> -->
        <!-- <el-button type="warning" @click="handleBatch" v-if="user.power*1 > 80">
          <i class="iconfont icon-jurassic_batch-work"></i>批量处理
        </el-button> -->
      </div>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="logList.filter(data => !searchKey.words || data.name.toLowerCase().includes(searchKey.words.toLowerCase()))"
      border stripe
      v-loading="loading" 
      :default-sort="{prop: 'dtCreate', order: 'ascending'}"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center"/> -->
      <!-- <el-table-column prop="status" label="用户状态" sortable width="115" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0?'success':'danger'">
            {{scope.row.status == 0?'正常':'停用'}}
          </el-tag> 
        </template>
      </el-table-column> -->
      <el-table-column prop="sn" label="设备序列号" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="model" label="操作模块" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="log" label="日志详情" sortable :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="dtOperator" label="操作时间" sortable width="180"> </el-table-column>
      <el-table-column prop="operator" label="操作人" sortable width="180" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="plat_user" label="所属用户" sortable width="180" :show-overflow-tooltip="true"> </el-table-column>
      <!-- <el-table-column label="操作" fixed="right" :width="user.power*1 == 99?200:100" align="center">
        <template #default="scope">
          <el-button v-if="user.power*1 == 99" type="warning" size="small" @click="getOwnerClient(scope.row.scope)">查看下属用户</el-button>
          <el-button type="success" size="small" @click="handleBtn(scope.$index, scope.row, 'edit')">编辑</el-button>
          <el-button type="warning" size="small" @click="handleBtn(scope.$index, scope.row, 'del')">状态</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <page-div ref="PAGING_COM" @change="pageChange" />
    <!-- dialog -->
    <client-dlg ref="CLIENT_DLG" @done="clientDone"/>
    <batch-dlg ref="BATCH_DLG" @done="clientDone"/>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import ClientDlg from '../dialog/ClientDlg.vue'
import ConditionQuery from '../fun_mod/ConditionQuery.vue'
import PageDiv from '../fun_mod/PageDiv.vue'
import http from '@/axios/http'
import util from '@/assets/js/util'
import BatchDlg from '../dialog/BatchDlg.vue'
import { ElNotification } from 'element-plus'
import mqtt from '@/assets/js/mqtt'
export default {
  components: { 
    ClientDlg,
    ConditionQuery,
    PageDiv,
    BatchDlg
  },
  props:['data'],
  setup() {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    onMounted(()=>{
      sessionStorage.removeItem('dBatchData')
      getLogs()
      mqttOnMsg()
    })

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 61) {
            let devFlag = sessionStorage.getItem('DEV_FLAG')
            if (devFlag == 'client_view') {
              for (let i in d) {
                let a = d[i].address
                if (!util.isNull(a)) {
                  d[i].wholeAddress = (a.province || '')+(a.city || '')+(a.district || '')+(a.addr || '')
                } else {
                  d[i].wholeAddress = ''
                }
                d[i].dtCreate = util.formatGmt(d[i].create_date)
                d[i].type = util.cilentType(d[i].scope)
              }
              logList.value = d
              paging.total = r.data.count
              if (PAGING_COM.value) PAGING_COM.value.setData(paging)
            }
          }
        }  
      })
    }

    let logList = ref([])
    let loading = ref(false)
    async function getLogs() {
      let d = [
        {sn: 'XTZ31242004343', model: '远程应用管理', log: '远程安装搜狗输入法com.sohu.inputmethod.sogou.SogouIMELauncher', dtOperator: '2024-08-20 14:02:26', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '远程应用管理', log: '远程卸载TeamViewer QuickSupport com.teamviewer.quicksupport', dtOperator: '2024-08-20 14:05:32', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '远程应用管理', log: '远程设置开机启动应用 测试工具', dtOperator: '2024-08-20 14:06:06', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '远程系统更新', log: '远程升级系统到V1.21-20240708[1.0.2] ', dtOperator: '2024-08-20 14:07:56', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '远程系统更新', log: '远程恢复出厂设置', dtOperator: '2024-08-20 14:15:26', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '远程重启关机', log: '远程关机操作', dtOperator: '2024-08-20 14:16:33', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '远程重启关机', log: '远程重启操作', dtOperator: '2024-08-20 14:18:16', operator: '测试用户操作员', plat_user: '测试用户'},
        {sn: 'XTZ31242004343', model: '终端信息', log: '设备参数详情查看，已安装应用查看', dtOperator: '2024-08-20 14:22:26', operator: '测试用户操作员', plat_user: '测试用户'},
      ]
      logList.value = d
      paging.total = 8
      if (PAGING_COM.value) PAGING_COM.value.setData(paging)
      return
      sessionStorage.setItem('DEV_FLAG','client_view')
      loading.value = true
      let msgCode = 61
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.name = searchKey.name
      m.contact = searchKey.contact
      m.phone = searchKey.phone
      m.province = searchKey.province
      m.city = searchKey.city
      if (searchKey.group) m.group = searchKey.group
      if (searchKey.qry_scope) m.qry_scope = searchKey.qry_scope
      if (searchKey.scope_length) m.scope_length = searchKey.scope_length
      if (typeof(searchKey.status)=='number') m.status = searchKey.status
      m.indexPage = paging.index
      m.pageSize = paging.size
      g.message = m
    //console.log('用户查询：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 多选
    let batchData = []
    function handleSelectionChange(e) {
      batchData = e
      sessionStorage.setItem('dBatchData',JSON.stringify(e))
    }

    // 分页
    let PAGING_COM = ref(null)
    let paging = reactive({
      total: 0,
      index: 1,
      size: 50
    })
    function pageChange(e) {
      paging.index = e
      getLogs()
    }
    // 搜索
    let searchKey = reactive({
      words: '',
      name: '',
      contact: '',
      phone: '',
      province: '',
      city: '',
      group: '',
      qry_scope: '',
      scope_length: '',
      status: 0,
      dtStart: '',
      dtEnd: '',
    })
    function searchDone(e) {
    //console.log(e)
      searchKey.words = ''
      searchKey.name = ''
      searchKey.contact = ''
      searchKey.phone = ''
      searchKey.province = ''
      searchKey.city = ''
      searchKey.group = ''
      searchKey.qry_scope = ''
      searchKey.scope_length = ''
      searchKey.dtStart = ''
      searchKey.status = ''
      searchKey.dtEnd = ''
      e.forEach(v=>{
        if (v.t == '用户名称') searchKey.name = v.v
        if (v.t == '联系人') searchKey.contact = v.v
        if (v.t == '电话') searchKey.phone = v.v
        if (v.t == 'province') searchKey.province = v.v
        if (v.t == 'city') searchKey.city = v.v
        if (v.t == '用户类型') searchKey.scope_length = v.v
        if (v.t == '状态') searchKey.status = v.v
        if (v.t == 'dtStart') searchKey.dtStart = v.v
        if (v.t == 'dtEnd') searchKey.dtEnd = v.v
      })
      paging.index = 1
      getLogs()
    }
    // 查看下属用户
    function getOwnerClient(qry_scope) {
    //console.log(qry_scope)
      searchKey.words = ''
      searchKey.name = ''
      searchKey.contact = ''
      searchKey.phone = ''
      searchKey.province = ''
      searchKey.city = ''
      searchKey.group = ''
      searchKey.qry_scope = qry_scope
      searchKey.scope_length = ''
      searchKey.dtStart = ''
      searchKey.status = ''
      searchKey.dtEnd = ''
      paging.index = 1
      getLogs()
    }
    // 编辑用户
    let CLIENT_DLG = ref(null)
    let clientInfo = ref({name: ''})
    function handleBtn(index,row,f) {
      //console.log(index, row)
      let bd = JSON.parse(sessionStorage.getItem('dBatchData')) || []
      let l = bd.length
      // if (l > 0) {
      //   ElNotification({
      //     type: 'warning',
      //     title: '当前已选中'+l+'条记录',
      //     message: '选中多条数据请使用批量处理'
      //   })
      //   return
      // }
      row.flag = f
      clientInfo.value = row
      CLIENT_DLG.value.open(clientInfo.value)
    }
    // 批量处理用户
    let BATCH_DLG = ref(null)
    function handleBatch() {
      let bd = JSON.parse(sessionStorage.getItem('dBatchData'))  || []
      if (batchData.length < bd.length) batchData = bd
      let e = {}
      e.flag = 'client'
      e.data = batchData
      BATCH_DLG.value.open(e)
    } 
    // 用户编辑完成
    function clientDone(e) {      
      setTimeout(()=>{
        getLogs()
      },1)  
    }

    function isNull(v) {
      return util.isNull(v)
    }

    return{
      user, logList, loading, handleSelectionChange, PAGING_COM, paging, pageChange, searchKey, searchDone, getOwnerClient,
      CLIENT_DLG,clientInfo, handleBtn, BATCH_DLG, handleBatch, clientDone, 
      isNull
    }
  },
}
</script>

<style lang="scss" scoped src="./tab_content.scss"></style>